package org.box.metadata.shell.web.servlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.buffer.CircularFifoBuffer;
import org.box.metadata.shell.web.WebConsoleCallback;
import org.box.metadata.shell.web.WebShell;

public class GSConsoleCallbackServlet extends ConsoleCallbackServlet {

	private static final long serialVersionUID = 1L;
	
	private final static Logger LOG = Logger
			.getLogger(GSConsoleCallbackServlet.class.getName());

	
	public GSConsoleCallbackServlet(WebShell shell,ByteArrayOutputStream outContent, int bufferSize) {
		super(shell, outContent, bufferSize);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected WebConsoleCallback createCallback(HttpServletRequest req, CircularFifoBuffer buffer) {
		int li = getLastIndex(req, null);
		String currentInput = shell.getCurrentInput();
		if (LOG.isLoggable(Level.FINE)) 
		    LOG.fine("LI: " + li + "; currentInput: " + currentInput);		

		
		return new WebConsoleCallback(buffer, li, null, currentInput != null);
	}
	

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		resp.setContentType("application/json; charset=utf-8");

		String cmd = req.getParameter("cmd");
		
		if (LOG.isLoggable(Level.FINE)) 
		    LOG.fine("cmd: " + cmd);		

        if (cmd != null && !cmd.trim().isEmpty())
        	shell.submitInput(cmd, null);
	}

}
